<?php
/**
 * User: @lose
 * Date: 2021/8/25
 * Time: 11:49 上午
 */

namespace Frieza\Modules\Circle\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Exceptions\InputErrorException;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\Circle\WhiteList;
use Doraemon\model\Circle\CircleBaseInfo as mCircleBaseInfo;
use Doraemon\model\Circle\DefaultTab as mDefaultTab;
use Doraemon\model\Circle\CircleRelatedLightTopic as mCircleRelatedLightTopic;
use Doraemon\model\LightTopic\LightTopic as mLightTopic;
use Doraemon\model\Topic\TopicActivity as mTopicActivity;
use Doraemon\service\Circle\CircleBaseAdmin as sCircleBaseAdmin;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\service\PublishSetting\CommonPublishSetting as sPublishSetting;
use Doraemon\service\Circle\DefaultTab as sDefaultTab;

class CircleBaseController
{
    public function index(Content $content, Request $request)
    {
        $where = $this->buildWhere($request->all());
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 15);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $order = ['circle_sort' => 'ASC', 'circle_id' => 'ASC'];

        $list = sCircleBaseAdmin::getList($where, $limit, $order);
        return $content
            ->header('圈子管理')
            ->breadcrumb(['text' => '圈子管理'])
            ->body($this->_formatGrid($list));
    }

    public function create(Content $content, $circleId = 0)
    {
        return $content
            ->header('圈子编辑')
            ->breadcrumb(['text' => '圈子管理', 'url' => 'circle'], ['text' => '圈子编辑'])
            ->row($this->_formatForm($circleId));
    }

    public function _formatForm($circleId)
    {
        $info = [];
        if ($circleId) {
            $info = sCircleBaseAdmin::getInfo($circleId);

            // 查询圈子关联的轻话题id
            $where = [
                'circle_id' => $circleId,
                'status' => mCircleRelatedLightTopic::STATUS_NORMAL,
                'ORDER' => ['light_topic_sort' => 'ASC']
            ];
            $circleRelatedLightTopicIds = mCircleRelatedLightTopic::getListByWhere($where, 'light_topic_id');
//            $lightTopics = mLightTopic::getLightTopicByIds($circleRelatedLightTopicIds, 'title');
            $lightTopics = mTopicActivity::getByIdsNotDel($circleRelatedLightTopicIds,  'title');
            $info['circle_related_light_topic'] = '';
            if (!empty($lightTopics)) {
                // 查询轻话题名称
                $info['circle_related_light_topic'] = implode("\r\n", $lightTopics);
            }
            $circlePublishSettingInfo = sPublishSetting::getCirclePublishSettingInfo($circleId);
            $info['circle_content_desc'] = $circlePublishSettingInfo['content_desc'] ?? '';
            $info['circle_suggestion'] = $circlePublishSettingInfo['suggestion'] ?? '';
            $info['default_tab_id'] = sDefaultTab::getDefaultTabId($circleId);
            $uidList = json_decode($info['white_uid_list'], true);
            $info['white_uid_list'] = !empty($uidList) ? implode(',', $uidList) : '';
        }
        $form = new Form($info);
        $form->hidden('circle_id', '圈子id');
        $form->text('circle_name', '圈子名称')->required()->placeholder('不超过 20个字符')->help('最多 20 个字符，1个中文1个字符，1个英文算1个字符');
        $form->text('circle_desc', '圈子简介')->required()->placeholder('不超过 30个字符')->help('最多 30 个字符，1个中文1个字符，1个英文算1个字符');
        $form->text('member_name', '成员名称')->required()->placeholder('不超过 10个字符')->help('最多 20 个字符，1个中文1个字符，1个英文算1个字符');
        $form->radio('can_join', '是否可加入')->options(mCircleBaseInfo::JOIN_MAP)->required();
        $form->imgUpload('circle_logo_id', '圈子图标', false)->help('建议尺寸 140（宽）*140（高）');
        $form->imgUpload('cover_id', '圈子封面', false)->help('建议尺寸 750（宽）375（高）');
        $form->textarea('circle_content_desc', '发布器默认文案');
        $form->textarea('circle_suggestion', '键盘上方正文小标题')->help('以英文逗号分隔，最多五条');
        $form->textarea('circle_related_light_topic', '关联话题')->placeholder('输入有id的话题标题，换行添加')->help('换行添加，最多七条');
        $form->textarea('white_uid_list', '设计师/装企白名单')->placeholder("输入uid,以英文逗号隔开")->help("输入uid,以英文逗号隔开");
        $form->radio('default_tab_id', '默认瀑布流')->options(mDefaultTab::TAB_MAP)->default(mDefaultTab::FEATURED_TAB);
        $form->action('/admin/circle/save');

        return $form->render();
    }

    public function save(Request $request)
    {
        $params = $request->all();

        if (mb_strlen($params['circle_name']) > 20) {
            throw new InputErrorException('不能超过20个字符', InputErrorException::DEFAULT_CODE, 'circle_name');
        }

        if (mb_strlen($params['member_name']) > 10) {
            throw new InputErrorException('不能超过10个字符', InputErrorException::DEFAULT_CODE, 'member_name');
        }

        if (mb_strlen($params['circle_desc']) > 30) {
            throw new InputErrorException('不能超过30个字符', InputErrorException::DEFAULT_CODE, 'circle_desc');
        }

        if (!$params['circle_logo_id']) {
            throw new InputErrorException('请上传圈子图标', InputErrorException::DEFAULT_CODE, 'circle_logo_id');
        }
        $circleContentDesc = $params['circle_content_desc'] ?? '';
        $circleSuggestion = trim(($params['circle_suggestion'] ?? ''), ',');
        if (!empty($circleSuggestion) && count(explode(',', $circleSuggestion)) > 5) {
            throw new InputErrorException('小建议最多支持5条', InputErrorException::DEFAULT_CODE, 'circle_suggestion');
        }

        if (!in_array($params['default_tab_id'], array_keys(mDefaultTab::TAB_MAP))) {
            throw new InputErrorException('取值范围异常', InputErrorException::DEFAULT_CODE, 'default_tab_id');
        }
        //圈子白名单逻辑
        $uidStr = str_replace(array("\r\n", "\r", "\n", " "), "", str_replace('，', ',', $params['white_uid_list']));
        $uidArr = explode(',', $uidStr);
        $whiteLists = array_filter($uidArr);
        $params['white_list'] = $whiteLists;
        $adminId = Admin::user()->id;
        $circleId = sCircleBaseAdmin::save($params['circle_id'], $params, $adminId);
        if ($circleId) {
            $circleRelatedLightTopic = array_filter(explode("\r\n", $params['circle_related_light_topic'] ?? ''));
            if (!empty($circleRelatedLightTopic)) {
                if (count($circleRelatedLightTopic) > 7) throw new InputErrorException('关联轻话题最多支持7个', InputErrorException::DEFAULT_CODE, 'circle_related_light_topic');
                // 参数里边的轻话题名称，查询轻话题id
                //$lightTopic = mLightTopic::getLightTopicByTitles($circleRelatedLightTopic, ['id', 'title']);
                $lightTopic = mTopicActivity::getListByKeywordNotDel($circleRelatedLightTopic, ['id', 'title']);
                $lightTopicMap = array_column($lightTopic, 'id', 'title');
                $sort = [];
                // 构建顺序
                foreach ($circleRelatedLightTopic as $key => $relatedLightTopic) {
                    $sort[$lightTopicMap[$relatedLightTopic]] = $key;
                }

                $lightTopicIds = array_column($lightTopic, 'id');
                if (!empty($lightTopicIds)) {
                    // 圈子轻话题关系表中关联的轻话题id
                    $lightTopicIdsByRelated = mCircleRelatedLightTopic::getListByWhere(['circle_id' => $circleId, 'status' => mCircleRelatedLightTopic::STATUS_NORMAL], 'light_topic_id');
                    $diffInsert = array_diff($lightTopicIds, $lightTopicIdsByRelated);
                    if (!empty($diffInsert)) {
                        $isCreateIds = [];
                        foreach ($diffInsert as $lightTopicId) {
                            // 先查询是否已经创建过
                            $isCreateIds[] = mCircleRelatedLightTopic::getByWhere(['circle_id' => $circleId, 'light_topic_id' => $lightTopicId], 'light_topic_id');
                        }

                        // 需要插入数据
                        $diffInsertSecond = array_diff($diffInsert, $isCreateIds);
                        if (!empty($diffInsertSecond)) {
                            $insertData = [];
                            foreach ($diffInsertSecond as $lightTopicIdInsert) {
                                $insertData[] = [
                                    'circle_id' => $circleId,
                                    'light_topic_id' => $lightTopicIdInsert,
                                    'light_topic_sort' => $sort[$lightTopicIdInsert],
                                    'create_time' => time()
                                ];
                            }
                            mCircleRelatedLightTopic::add($insertData);
                        }

                        // 需要更新为正常的数据. 这一步是将之前删除过的数据置为正常状态
                        $diffUpdateSecond = array_intersect($diffInsert, $isCreateIds);
                        if (!empty($diffUpdateSecond)) {
                            foreach ($diffUpdateSecond as $lightTopicIdUpdate) {
                                mCircleRelatedLightTopic::updateByWhere(
                                    [
                                        'circle_id' => $circleId,
                                        'light_topic_id' => $lightTopicIdUpdate,
                                    ],
                                    [
                                        'status' => mCircleRelatedLightTopic::STATUS_NORMAL,
                                        'update_time' => time(),
                                        'light_topic_sort' => $sort[$lightTopicIdUpdate],
                                    ]);
                            }
                        }
                    }

                    // 这一步是更新已有轻话题的顺序
                    $diffUpdate = array_intersect($lightTopicIds, $lightTopicIdsByRelated);
//                    var_dump($lightTopicIds, $lightTopicIdsByRelated, $diffUpdate, $sort);die;
                    if (!empty($diffUpdate)) {
                        foreach ($diffUpdate as $diffUpdateValue) {
                            mCircleRelatedLightTopic::updateByWhere(
                                [
                                    'circle_id' => $circleId,
                                    'light_topic_id' => $diffUpdateValue,
                                ],
                                [
                                    'status' => mCircleRelatedLightTopic::STATUS_NORMAL,
                                    'update_time' => time(),
                                    'light_topic_sort' => $sort[$diffUpdateValue],
                                ]);
                        }
                    }

                    // 需要删除的数据
                    $diffDelete = array_diff($lightTopicIdsByRelated, $lightTopicIds);
                    if (!empty($diffDelete)) {
                        foreach ($diffDelete as $diffDeleteValue) {
                            mCircleRelatedLightTopic::updateByWhere(
                                [
                                    'circle_id' => $circleId,
                                    'light_topic_id' => $diffDeleteValue,
                                ],
                                [
                                    'status' => mCircleRelatedLightTopic::STATUS_DELETE,
                                    'update_time' => time()
                                ]);
                        }
                    }
                }
            } else {
                mCircleRelatedLightTopic::updateByWhere(
                    [
                        'circle_id' => $circleId,
                    ],
                    [
                        'status' => mCircleRelatedLightTopic::STATUS_DELETE,
                        'update_time' => time()
                    ]);
            }

            if (!empty($circleContentDesc) || !empty($circleSuggestion)) {
                sPublishSetting::saveCirclePublishSetting($circleId, $circleContentDesc, $circleSuggestion, $adminId);
            }

            sDefaultTab::save($circleId, $params['default_tab_id']);

            WhiteList::delWhiteListByCircleId($circleId);
            if (!empty($whiteLists)) {
                //白名单总体缓存
                WhiteList::setWhiteListByCircleId($circleId, json_encode($whiteLists));
            }

            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/circle')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public function _formatGrid($list)
    {
        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'keyName' => 'circle_id'
        ]);

        return Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->paginate(15);
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->equal('circle_name', '圈子名称');
                });

                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->column('circle_id', '圈子ID')->sort('circle/sort');
                $grid->column('circle_name', '圈子名称');
                $grid->column('proportion', '流量比例%')->default(0);
                $grid->column('admin_id', '创建人')->display(function () {
                    return Admin::user()->find($this->admin_id)->name;
                });
                $grid->column('addtime', '创建时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->addtime);
                });
                $grid->column('user_total', '成员数')->default(0);
                $grid->column('yesterday_user_count', '昨日新增成员');
                $grid->column('content_total', '内容数')->default(0);
                $grid->column('yesterday_content_count', '昨日新增内容');

                $grid->tools(function (Grid\Tools $tool) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, 'proportion/edit', '配置流量比例'));
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->row->setKeyName('circle_id');
                    $actions->disableDelete();
                    $actions->append('<a href="circle/user/' . $actions->row->circle_id . '" target="_blank" class="fa fa-eye">查看成员</a>');
                    $actions->append('<a href="circle/tab/' . $actions->row->circle_id . '" target="_blank" class="fa fa-empire">高级</a>');
                });
            }
        );
    }

    private function buildWhere($params)
    {
        $where = ['circle_status' => mCircleBaseInfo::STATUS_NORMAL];
        if ($params['circle_name']) {
            $where['circle_name[~]'] = $params['circle_name'];
        }
        return $where;
    }

    public function sort(Request $request)
    {
        $params = $request->all();
        $sortList = $params['sort'];


        foreach ($sortList as $circleId => $sort) {
            $data = [
                'circle_sort' => $sort,
                'edittime' => time()
            ];
            mCircleBaseInfo::edit($circleId, $data);
        }
    }
}